Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
由題意得知,提供一個函式,此函式有二個參數,第一個參數是一個陣列(nums),第二個參數則為常數(n),借由第二個參數來將陣列(nums)切出二個陣列再重新進行合併,最終回傳合併後的陣列。
var shuffle = function(nums, n) {
if(nums.length % n === 0)
{
let num1 = nums.slice(0, n)
let num2 = nums.slice(n)
let result = num1.map((i, idx) => {
return [i, num2[idx]];
});
return result.flat();
}
return nums;
};
Array.slice()
var a = [1, 2, 3, 4, 5];
a.slice(0, 3); // 回傳 [1, 2, 3];
a.slice(3); // 回傳 [4, 5];
a.slice(1, -1); // 回傳 [2, 3, 4];
a.slice(-3, -2); // 回傳 [3];
var a = [1, 2, 3];
var b = a.slice(0); // [1, 2, 3];
b.push(4); // [1, 2, 3, 4];
a; // [1, 2, 3];